engines.all().map((ScriptEngine) => {
  if (engines.myEngine().toString() !== ScriptEngine.toString()) {
    ScriptEngine.forceStop();
  }
});
$settings.setEnabled("foreground_service", true);
if (!requestScreenCapture()) {
  toastLog("请求截图失败");
  exit();
}

if (!floaty.checkPermission()) {
  toastLog("请先开启悬浮窗权限");
  setTimeout(function () {
    app.startActivity({
      action: "android.settings.action.MANAGE_OVERLAY_PERMISSION",
      data: "package:" + context.packageName,
    });
  }, 1000);
}
setInterval(() => {}, 1000);
let w = floaty.rawWindow(
  <vertical>
    <button id="screenshot" bg="#2196f3" w="60dp" h="50dp">
      截图
    </button>
  </vertical>
);
ui.post(function () {
  let ww = w.getWidth();
  let wh = w.getHeight();
  let left = (device.width - ww) / 2;
  let top = (device.height - wh) / 2;
  w.setPosition(left, top);
});
events.on("exit", function () {
  w.close();
});
let clickAction = function () {
  ui.run(function () {
    w.screenshot.attr("bg", "#4caf50");
  });
  ui.post(function () {
    w.screenshot.attr("bg", "#2196f3");
  }, 300);
  let img = captureScreen();
  let imgName = timeFromDate() + ".png";
  let imgPath = files.join(files.getSdcardPath(), "脚本/screenshot", imgName);
  log(imgPath);
  files.createWithDirs(imgPath);
  img.saveTo(imgPath);
  upload(imgPath);
  toastLog("截图上传成功");
};
setOnTouchListener(w, w.screenshot, clickAction);
function timeFromDate() {
  return new Date().toTimeString().slice(0, 8).replace(/:/g, "_");
}
function upload(filepath) {
  let url = "http://192.168.101.24:3000/file-upload";

  var res = http.postMultipart(url, {
    file: open(filepath),
  });
  log(res.body.string());
}

function setOnTouchListener(floatyWindow, childView, clickAction) {
  //记录按键被按下时的触摸坐标
  var x = 0,
    y = 0;
  //记录按键被按下时的悬浮窗位置
  var windowX, windowY;
  //记录按键被按下的时间以便判断长按等动作
  var downTime;
  childView.setOnTouchListener(function (view, event) {
    switch (event.getAction()) {
      case event.ACTION_DOWN:
        x = event.getRawX();
        y = event.getRawY();
        windowX = floatyWindow.getX();
        windowY = floatyWindow.getY();
        downTime = new Date().getTime();
        return true;
      case event.ACTION_MOVE:
        //移动手指时调整悬浮窗位置
        floatyWindow.setPosition(windowX + (event.getRawX() - x), windowY + (event.getRawY() - y));
        return true;
      case event.ACTION_UP:
        //手指弹起时如果偏移很小则判断为点击
        if (Math.abs(event.getRawY() - y) < 5 && Math.abs(event.getRawX() - x) < 5) {
          clickAction();
        }

        return true;
    }
    return true;
  });
}
